<!DOCTYPE html>
<html>

<head>
  <title>Canvas 路牌优化样式</title>
  <style>
    body {
      margin: 0;
      padding: 0;
      background-color: #f1f1f1;
    }
  </style>
</head>

<body>
  <script>

    let base64Data = ''
    async function createImageFromText(text, fontSize = 24, iconUrl) {
      if (text.length == 1) {
        text = ` ${text} `
      }
      let words = text.split('、')
      let maxWord = words.reduce((a, b) => {
        return a.length > b.length ? a : b;
      });
      // 创建一个新的canvas元素
      const canvas = document.createElement('canvas');
      const icon = new Image();

      icon.setAttribute('crossorigin', 'anonymous');
      icon.src = iconUrl;

      await new Promise(resolve => {
        icon.onload = function () {
          resolve()
        }
      })

      function wrapText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split('、');
        var line = '';
        for (var n = 1; n <= words.length; n++) {

          var testLine = words[n-1];
          // var metrics = context.measureText(testLine);
          var testWidth = getTextWidth(testLine, fontSize);
          context.fillText(testLine, (maxWidth / 2 - testWidth / 2) < 0 ? 0 : (maxWidth / 2 - testWidth / 2), n * lineHeight);
        }

      }


      // 设置canvas的宽度和高度以适应文本
      const width = canvas.width = getTextWidth(maxWord, fontSize);
      const height = canvas.height = words.length * fontSize * 1.3 + fontSize * 3.5;
      // 获取canvas的2d上下文
      const ctx = canvas.getContext('2d');

      // 设置字体大小和颜色
      ctx.font = fontSize + 'px cursive';
      ctx.fillStyle = 'red';
      ctx.drawImage(icon, width / 2 - fontSize * 3.3 / 2, words.length * fontSize * 1.2 , fontSize * 3.3, fontSize * 3.3);
      // 绘制文本
      // ctx.fillText(text, 0, fontSize);
      wrapText(ctx, text, 0, fontSize, width, fontSize * 1.2)

      const base64 = canvas.toDataURL();

      return base64;
    }

    function getTextWidth(text, fontSize) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.font = fontSize + 'px Arial';
      return ctx.measureText(text).width;
    }


    (async () => {
      const base64 = await createImageFromText('舞蹈室、撒打算大、啊完卫生、撒的大富大贵风蛋糕', 18, base64Data);
      const mage = new Image();
      // console.log(base64);
      mage.src = base64
      document.body.appendChild(mage);
    })()


  </script>
</body>

</html>